package controller;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.TagModel;
import entity.Tag;

/**
 * Servlet implementation class ListTag
 */
@WebServlet("/ListTag")
public class ListTag extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Language
		HttpSession session = request.getSession(true);
		ResourceBundle resource = null;
		if (session.getAttribute("language") != null) {
			resource = (ResourceBundle) session.getAttribute("language");

		} else {
			resource = ResourceBundle.getBundle("en", new Locale("en"));
			session.setAttribute("language", resource);
		}

		// Paginate
		int currentPage = 0;
		String path = ((HttpServletRequest) request).getRequestURI();
		String[] splittedURI = path.split("/");
		if (splittedURI.length == 4) {
			currentPage = Integer.valueOf(splittedURI[3]);
		}

		// Property handle	

		// Return view
		TagModel tagModel = new TagModel();
		List<Tag> list = tagModel.all(currentPage);
		if (list.size() > 0) {
			request.setAttribute("currentPage", currentPage);
			request.setAttribute("listTag", list);
			request.getRequestDispatcher("/list_tag.jsp").forward(request,
					response);
		} else {
			if (currentPage == 0) {
				request.getRequestDispatcher("/erro.jsp").forward(request,
						response);
			} else {
				list = tagModel.all(0);
				request.setAttribute("currentPage", 0);
				request.setAttribute("listTag", list);
				request.getRequestDispatcher("/list_tag.jsp").forward(
						request, response);
			}
		}
	}

}
